{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Google AlloyDB for PostgreSQL - `AlloyDBReader`\n",
    "\n",
    "> [AlloyDB](https://cloud.google.com/alloydb) is a fully managed relational database service that offers high performance, seamless integration, and impressive scalability. AlloyDB is 100% compatible with PostgreSQL. Extend your database application to build AI-powered experiences leveraging AlloyDB's LlamaIndex integrations.\n",
    "\n",
    "This notebook goes over how to use `AlloyDB for PostgreSQL` to retrieve data as documents with the `AlloyDBReader` class.\n",
    "\n",
    "Learn more about the package on [GitHub](https://github.com/googleapis/llama-index-alloydb-pg-python/).\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/llama-index-alloydb-pg-python/blob/main/samples/llama_index_reader.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Before you begin\n",
    "\n",
    "To run this notebook, you will need to do the following:\n",
    "\n",
    " * [Create a Google Cloud Project](https://developers.google.com/workspace/guides/create-project)\n",
    " * [Enable the AlloyDB API](https://console.cloud.google.com/flows/enableapi?apiid=alloydb.googleapis.com)\n",
    " * [Create a AlloyDB cluster and instance.](https://cloud.google.com/alloydb/docs/cluster-create)\n",
    " * [Create a AlloyDB database.](https://cloud.google.com/alloydb/docs/quickstart/create-and-connect)\n",
    " * [Add a User to the database.](https://cloud.google.com/alloydb/docs/database-users/about)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 🦙 Library Installation\n",
    "Install the integration library, `llama-index-alloydb-pg`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Colab only:** Uncomment the following cell to restart the kernel or use the button to restart the kernel. For Vertex AI Workbench you can restart the terminal using the button on top."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Automatically restart kernel after installs so that your environment can access the new packages\n",
    "# import IPython\n",
    "\n",
    "# app = IPython.Application.instance()\n",
    "# app.kernel.do_shutdown(True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 🔐 Authentication\n",
    "Authenticate to Google Cloud as the IAM user logged into this notebook in order to access your Google Cloud Project.\n",
    "\n",
    "* If you are using Colab to run this notebook, use the cell below and continue.\n",
    "* If you are using Vertex AI Workbench, check out the setup instructions [here](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from google.colab import auth\n",
    "\n",
    "auth.authenticate_user()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ☁ Set Your Google Cloud Project\n",
    "Set your Google Cloud project so that you can leverage Google Cloud resources within this notebook.\n",
    "\n",
    "If you don't know your project ID, try the following:\n",
    "\n",
    "* Run `gcloud config list`.\n",
    "* Run `gcloud projects list`.\n",
    "* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.\n",
    "\n",
    "PROJECT_ID = \"my-project-id\"  # @param {type:\"string\"}\n",
    "\n",
    "# Set the project id\n",
    "!gcloud config set project {PROJECT_ID}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Usage"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set AlloyDB database values\n",
    "Find your database values, in the [AlloyDB Instances page](https://console.cloud.google.com/alloydb/clusters)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# @title Set Your Values Here { display-mode: \"form\" }\n",
    "REGION = \"us-central1\"  # @param {type: \"string\"}\n",
    "CLUSTER = \"my-cluster\"  # @param {type: \"string\"}\n",
    "INSTANCE = \"my-primary\"  # @param {type: \"string\"}\n",
    "DATABASE = \"my-database\"  # @param {type: \"string\"}\n",
    "TABLE_NAME = \"document_store\"  # @param {type: \"string\"}\n",
    "USER = \"postgres\"  # @param {type: \"string\"}\n",
    "PASSWORD = \"my-password\"  # @param {type: \"string\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### AlloyDBEngine Connection Pool\n",
    "\n",
    "One of the requirements and arguments to establish AlloyDB Reader is a `AlloyDBEngine` object. The `AlloyDBEngine`  configures a connection pool to your AlloyDB database, enabling successful connections from your application and following industry best practices.\n",
    "\n",
    "To create a `AlloyDBEngine` using `AlloyDBEngine.from_instance()` you need to provide only 5 things:\n",
    "\n",
    "1. `project_id` : Project ID of the Google Cloud Project where the AlloyDB instance is located.\n",
    "1. `region` : Region where the AlloyDB instance is located.\n",
    "1. `cluster`: The name of the AlloyDB cluster.\n",
    "1. `instance` : The name of the AlloyDB instance.\n",
    "1. `database` : The name of the database to connect to on the AlloyDB instance.\n",
    "\n",
    "By default, [IAM database authentication](https://cloud.google.com/alloydb/docs/connect-iam) will be used as the method of database authentication. This library uses the IAM principal belonging to the [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) sourced from the environment.\n",
    "\n",
    "Optionally, [built-in database authentication](https://cloud.google.com/alloydb/docs/database-users/about) using a username and password to access the AlloyDB database can also be used. Just provide the optional `user` and `password` arguments to `AlloyDBEngine.from_instance()`:\n",
    "\n",
    "* `user` : Database user to use for built-in database authentication and login\n",
    "* `password` : Database password to use for built-in database authentication and login.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** This tutorial demonstrates the async interface. All async methods have corresponding sync methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index_alloydb_pg import AlloyDBEngine\n",
    "\n",
    "engine = await AlloyDBEngine.afrom_instance(\n",
    "    project_id=PROJECT_ID,\n",
    "    region=REGION,\n",
    "    cluster=CLUSTER,\n",
    "    instance=INSTANCE,\n",
    "    database=DATABASE,\n",
    "    user=USER,\n",
    "    password=PASSWORD,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create AlloyDBReader"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When creating an `AlloyDBReader` for fetching data from AlloyDB, you have two main options to specify the data you want to load:\n",
    "* using the table_name argument - When you specify the table_name argument, you're telling the reader to fetch all the data from the given table.\n",
    "* using the query argument - When you specify the query argument, you can provide a custom SQL query to fetch the data. This allows you to have full control over the SQL query, including selecting specific columns, applying filters, sorting, joining tables, etc.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Documents using the `table_name` argument"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Load Documents via default table\n",
    "The reader returns a list of Documents from the table using the first column as text and all other columns as metadata. The default table will have the first column as\n",
    "text and the second column as metadata (JSON). Each row becomes a document."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index_alloydb_pg import AlloyDBReader\n",
    "\n",
    "# Creating a basic AlloyDBReader object\n",
    "reader = await AlloyDBReader.create(\n",
    "    engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    # schema_name=SCHEMA_NAME,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Load documents via custom table/metadata or custom page content columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "reader = await AlloyDBReader.create(\n",
    "    engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    # schema_name=SCHEMA_NAME,\n",
    "    content_columns=[\"product_name\"],  # Optional\n",
    "    metadata_columns=[\"id\"],  # Optional\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Documents using a SQL query\n",
    "The query parameter allows users to specify a custom SQL query which can include filters to load specific documents from a database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table_name = \"products\"\n",
    "content_columns = [\"product_name\", \"description\"]\n",
    "metadata_columns = [\"id\", \"content\"]\n",
    "\n",
    "reader = AlloyDBReader.create(\n",
    "    engine=engine,\n",
    "    query=f\"SELECT * FROM {table_name};\",\n",
    "    content_columns=content_columns,\n",
    "    metadata_columns=metadata_columns,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note**: If the `content_columns` and `metadata_columns` are not specified, the reader will automatically treat the first returned column as the document’s `text` and all subsequent columns as `metadata`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set page content format\n",
    "The reader returns a list of Documents, with one document per row, with page content in specified string format, i.e. text (space separated concatenation), JSON, YAML, CSV, etc. JSON and YAML formats include headers, while text and CSV do not include field headers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "reader = await AlloyDBReader.create(\n",
    "    engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    # schema_name=SCHEMA_NAME,\n",
    "    content_columns=[\"product_name\", \"description\"],\n",
    "    format=\"YAML\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the documents\n",
    "\n",
    "You can choose to load the documents in two ways:\n",
    "* Load all the data at once\n",
    "* Lazy load data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Load data all at once"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = await reader.aload_data()\n",
    "\n",
    "print(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Lazy Load the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "docs_iterable = reader.alazy_load_data()\n",
    "\n",
    "docs = []\n",
    "async for doc in docs_iterable:\n",
    "    docs.append(doc)\n",
    "\n",
    "print(docs)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
